package com.hs.auth.action;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.AUTHConstant;
import com.hs.auth.model.HsAccount;
import com.hs.auth.service.IUserService;
import com.hs.core.action.BaseAction;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.BigNumCal;
import com.hs.core.utils.MD5;
@Controller  
public class LogController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(LogController.class);
	private IUserService userService;
	 @Autowired  
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	 /**
	  * 用户登录
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */ 
	@RequestMapping(value="/logon.do")   
	public ModelAndView logon(HttpServletRequest request,
			HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException { 
		StringBuffer buffer = new StringBuffer();
		String viewname = "logon";
		String uid = request.getParameter("UserName");
		String password = request.getParameter("Password");
		String rememberme = request.getParameter("rememberme");
		logger.debug("rememberme:" + rememberme);
		if("1".equals(rememberme)){
			rememberMe(uid,password,response);
		}
		logger.debug("uid:" + request.getParameter("UserName"));
		HsAccount obj = userService.getAccByUid(uid);
 		//根据用户名查询帐号信息
		if(null != obj){
			String dbpassword = obj.getPassword();
			String inputpwd = MD5.md5(password);
			if(inputpwd.equals(dbpassword)){
				viewname = "index";
				this.initSession(request, obj);
				//this.loadAuth(request,obj.getId()+"");
				this.putUserPowerInsession(request,obj.getId());
				System.out.println("session：" +(Map)request.getSession().getAttribute("USERROLE_"+obj.getId()));

			} else{
				buffer.append("密码输入错误!");
			}
		}else{
			 buffer.append("【").append(uid).append("】").append("不存在!");
		}   
		
		modelMap.put("alert", buffer.toString());
		modelMap.put("username", uid);
		logger.debug("alert:" + buffer.toString());
		return new ModelAndView(viewname,modelMap);  
	}
	private void rememberMe(String uid,String pwd,HttpServletResponse response){
		Cookie u = new Cookie("csdaname",uid); 
		Cookie p = new Cookie("csdapwd",pwd); 

 		u.setMaxAge(30*24*60*60); //设置过期之前的最长时间    
  		//设置Cookie路径和域名 
 		//c.setDomain("cintcm.ac.cn") ;
 		p.setMaxAge(30*24*60*60);
 		response.addCookie(u); 
 		response.addCookie(p); 

	}
	 /**
	  * 用户登出
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/logout.do")   
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		StringBuffer buffer = new StringBuffer(); 
		logger.info("In the logController logout method!");
		HttpSession session = request.getSession();
		String userId = "";
		String userName = "";
		HsAccount accinfo = (HsAccount)session.getAttribute(AUTHConstant.USERINSESSION);
		if(null != accinfo){
			userId = accinfo.getId()+"";
 		}
		session.setAttribute(AUTHConstant.USERINSESSION, null); 
		session.setAttribute("USERPOWER_" + userId, null);
		//LogUtil.log(req,userName+"-退出系统",LogUtil.LOG_OUT,userId);
		if(null != session)
			session.invalidate(); 
		return new ModelAndView("logon");  
	}
	/**
	  * 用户登出
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/logoncontent.do")   
	public ModelAndView logoncontent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		 
		Map data = new HashMap();
 		DBMgr inst = this.getDbo(request);
 		StringBuffer onesql = new StringBuffer("select years,to_char(count(*)) as count from (select substr(YEARSTR,0,4) as years,id　from CHD_PAPERINFO where datatype=1 and YEARSTR is not null ) group by years");
 		StringBuffer twosql = new StringBuffer("select years,to_char(count(*)) as count from (select substr(YEARSTR,0,4) as years,id　from CHD_PAPERINFO where datatype=1 and YEARSTR is not null ) group by years");
 		StringBuffer threesql = new StringBuffer("select years,to_char(count(*)) as count from (select substr(YEARSTR,0,4) as years,id　from CHD_PAPERINFO where datatype=1 and YEARSTR is not null ) group by years");
 		List list1 = inst.queryList(onesql.toString(), null);
 		List list2 = inst.queryList(twosql.toString(), null); 
 		List list3 = inst.queryList(threesql.toString(), null);
        StringBuffer year1str = new StringBuffer();
        StringBuffer data1str = new StringBuffer();
        StringBuffer year2str = new StringBuffer();
        StringBuffer data2str = new StringBuffer();
        StringBuffer year3str = new StringBuffer();
        StringBuffer data3str = new StringBuffer();
 		for(int i =0;i<list1.size();i++){
 			Map m1 = (Map)list1.get(i);
 			String years = (String)m1.get("years");
 			String countstr = (String)m1.get("count");
 			logger.debug("years:" + years);
 			if(BigNumCal.isNumeric(years)){
 				year1str.append("'").append(years).append("',");
 				data1str.append(countstr).append(",");
 			}else{
 				continue;
 			}
 			logger.debug("data1str:" + data1str);
 		}
 		for(int j =0;j<list2.size();j++){
 			Map m2 = (Map)list2.get(j);
 			String years = (String)m2.get("years");
 			String countstr = (String)m2.get("count");
 			if(BigNumCal.isNumeric(years)){
 				year2str.append("'").append(years).append("',");
 				data2str.append(countstr).append(",");
 			}else{
 				continue;
 			}
 		}
 		for(int k =0;k<list3.size();k++){
 			Map m3 = (Map)list3.get(k);
 			String years = (String)m3.get("years");
 			String countstr = (String)m3.get("count");
 			if(BigNumCal.isNumeric(years)){
 				year3str.append("'").append(years).append("',");
 				data3str.append(countstr).append(",");
 			}else{
 				continue;
 			}
 		}
 		data.put("year1str", year1str.substring(0,year1str.length()-1).toString());
 		data.put("year2str", year2str.substring(0,year2str.length()-1).toString());
 		data.put("year3str", year3str.substring(0,year3str.length()-1).toString());
 		data.put("data1str", data1str.substring(0,data1str.length()-1).toString());
 		data.put("data2str", data2str.substring(0,data2str.length()-1).toString());
 		data.put("data3str", data3str.substring(0,data3str.length()-1).toString());
		return new ModelAndView("/logon",data);  
	} 
	 
	 
}
